<template>
	<!--index.wxml-->
	<view class="container">

		<view>
			<!-- 输入框示例 -->
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose" mode="base" title="加入购物车" @confirm="dialogConfirm"
					@close="dialogClose">
					<view>
						<view style="padding: 3rpx;">商品名称：{{ detail.title }}</view>
						<view style="padding: 3rpx;">商品图片:<image :src="detail.image"
								style="width: 150px;height: 150px;  vertical-align: middle;"></image>
						</view>

						<view style="padding: 3rpx;">商品编码：{{ detail.code }}</view>
						<view style="padding: 3rpx;">商品类型：{{ detail.type }}</view>
						<view style="padding: 3rpx;">货架区域：{{ detail.shelves }}</view>
						<view style="padding: 3rpx;display: flex;align-items: center;">数量：
							<uni-number-box :min="1" v-model="detail.stock" @change="change" @focus="focus" />
						</view>
						<view style="padding: 3rpx;">价格:<text style="color: red;font-size: 46rpx;">￥{{ price
						}}</text></view>
					</view>
				</uni-popup-dialog>
			</uni-popup>

		</view>

		<swiper>
			<block>
				<swiper-item>

					<image class="slide-image" width="355" height="150" />
				</swiper-item>
			</block>
		</swiper>
		<view class='qcode_outer' @click='goscan()'>
			<view class='qcode_inner'>
				<image class="qrcode_image" src='../../static/images/qrcode.png'></image>
				<text class='qcode_text'>请扫描商品条形码</text>
			</view>
		</view>
		<view class="action-section1" v-show="isShow">
			<button type="primary" class="no-border tip-btn" @click="wbarcode">扫不出来试试手动输入条码</button>
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import { isEmptyObj, inWechat } from '../../utils/index.js';
import config from '../../config/index.js';
export default {
	data() {
		return {
			swiperCurrent: 0,
			// 详情
			detail: {
				title: '',
				id: '',
				image: '',
				price: 0,
				code: '',
				stock: 1,
				type: '',
				shelves: ''
			},
			price: 0,
			isShow: true,
			goodsList: []
		}
	},
	computed: {
		...mapState('user', ['token', 'openid', 'userinfo']),
		...mapState('ad', ['homeSwider', 'homeAd', 'homeLogo']),
		...mapState('category', ['homeTop']),
		...mapState('goods', ['homeGoods']),
		...mapState('cart', ['mycart']),
	},
	onShow() {
		//#ifdef H5
		//#endif
	},

	onLoad() {
	},
	onPullDownRefresh() {
	},
	methods: {
		...mapMutations('cart', ['setCart', 'clearCart']),
		...mapMutations('user', ['setOpenId']),
		...mapMutations('ad', ['setHomeAd', 'setHomeSwider', 'setHomeLogo']),
		...mapMutations('category', ['setHomeTop']),
		...mapMutations('goods', ['setHomeGoods']),
		wbarcode() {
			return uni.navigateTo({
				url: '/pages/cart/barcode'
			})
		},
		goscan() {
			if (!this.token) {
				uni.navigateTo({
					url: '/pages/public/login'
				})
				return this.$api.msg('请先登录')
			}
			const that = this
			uni.scanCode({
				success: function (res) {
					if (res.result) {
						that.$ajax.get('commodity/getByPage?code=' + res.result).then(data => {
							if (data.result.total > 0) {
								const { title, id, image, money2, code, type, shelves } = data.result.records[0]
								that.detail.title = title
								that.detail.image = image
								that.price = money2
								that.detail.price = money2
								that.detail.code = code
								that.detail.type = type
								that.detail.shelves = shelves
								that.detail.id = id
								that.$refs.inputDialog.open()
								that.isShow = false
							} else {
								return that.$toast('没有找到该商品')
							}
						})
					} else {
						that.$toast('扫码失败')
					}
				},
				fail: function () {
					that.$toast('扫码失败')
				}
			})
		},
		//#ifdef H5
		getCode() {    //静默授权，拉取openid
			if (1 == config.isDevelop) {
				return;
			}
			if (this.openid.length > 0) {
				return;
			}
			let code = this.getUrlParam('code')
			let appid = '';
			if (code == null || code === '') {
				let url = 'https://open.weixin.qq.com/connect/oauth2/authorize'
					+ '?appid=' + appid
					+ '&redirect_uri=' + config.domain + 'h5/'
					+ '&response_type=code'
					+ '&scope=snsapi_base&state=123#wechat_redirect';
				window.location.href = url;
			} else {
				this.getOpenId(code)
			}
		},
		getUrlParam(name) {
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location) || [, ''])[1].replace(/\+/g, '%20')) || null
		},
		getOpenId(code) {
			if (!this.token) return;
			let p = { token: this.token, code: code };
			this.$ajax.get('wechat/createopenid', p).then(data => {
				if (0 == data.error) {
					this.setOpenId(data.data);
				}
			});
		},
		//#endif

		//加载各类别商品 每个类别6个
		loadGoods() {
			// this.$ajax.get('goods/home_category',{}).then(data=>{
			// 	if(0==data.error){
			// 		this.setHomeGoods(data.data);
			// 	}
			// 	uni.stopPullDownRefresh();
			// })
		},

		//加载广告
		loadSwiderAd() {
			// this.$ajax.get('adv/index',{'position':1}).then(data=>{
			// 	if(0==data.error){

			// 		this.setHomeSwider(data.data);
			// 	}
			// 	uni.stopPullDownRefresh();
			// })
		},
		loadHomeAd() {
			// this.$ajax.get('adv/index',{'position':4}).then(data=>{
			// 	if(0==data.error){
			// 		this.setHomeAd(data.data);
			// 	}
			// 	uni.stopPullDownRefresh();
			// })
		},
		loadHomeLogo() {
			// this.$ajax.get('adv/index',{'position':3}).then(data=>{
			// 	console.log(data);
			// 	if(0==data.error){
			// 		this.setHomeLogo(data.data[0]);
			// 	}
			// })
		},
		loadCate() {
			// this.$ajax.get('category/gettop',{}).then(data=>{
			// 	if(0==data.error){
			// 		this.setHomeTop(data.data);
			// 	}
			// 	uni.stopPullDownRefresh();
			// })
		},
		//轮播图切换修改背景色
		swiperChange(e) {
			const index = e.detail.current;
			this.swiperCurrent = index;
		},
		//详情页
		navToGoodsDetail(item) {
			// return uni.navigateTo({
			// 	url: `/pages/product/product?data=${JSON.stringify({
			// 		goods: item
			// 	})}`
			// });
		},
		navToList(cid) {
			uni.navigateTo({
				url: '../product/list?cid=' + cid
			})
		},
		//点击地址
		nvAddressTap() {
			return uni.navigateTo({
				url: '/pages/shop/shop',
			});
		},
		change(value) {
			console.log(value);
			this.detail.stock = value;
			const handleDecimalPrecision = (value, fixedNum = 2, multiple = 1) => {
				return parseFloat((value * multiple).toFixed(fixedNum))
			}
			this.price = handleDecimalPrecision(value, 2, this.detail.price);
		},
		focus(e) {
			console.log('focus:', e);
		},
		dialogClose() {
			console.log('点击关闭')
			this.isShow = true;
		},
		dialogConfirm() {
			console.log('点击确认')
			const params = {
				tablename: this.detail.title,
				goodid: this.detail.id,
				goodname: this.detail.title,
				picture: this.detail.image,
				buynumber: this.detail.stock,
				userid: this.userinfo.id,
				price: this.detail.price,
				discountprice: 0,
			};
			// console.log(params);
			// 先去判断数据库是否有这个商品，有则修改数量，没有则添加
			const obj = {
				userid: this.userinfo.id,
				goodid: this.detail.id,
			}
			console.log(obj);
			// 查询购物车是否有该商品，根据goodid
			this.$ajax.get('cart/queryListByGoodId', obj).then(res => {
				console.log(res);
				if (res.success) {
					console.log(res.result.length);
					if (res.result.length > 0) {
						this.$toast('商品已存在购物车,请点击购物车查看!');
						this.detail.stock = 1; //重置数量
						return;
					}
					this.$ajax.get('cart/save', params).then(res => {
						console.log(res);
						if (res.success) {
							this.$refs.inputDialog.close();
							this.isShow = true;
							console.log("添加到购物车成功")
							this.$toast(res.message)
							this.detail.stock = 1; //重置数量
						}
					}).catch(err => {
						this.$toast(err.message)
						this.$refs.inputDialog.close();
						this.isShow = true;
						this.detail.stock = 1; //重置数量
					})
				}
			})
		},

	},
}
</script>

<style lang="scss">
@import "../../static/css/common.scss";

/**index.wxss**/
uni-modal .uni-modal__bd {
	white-space: pre-wrap;
}


.qcode_outer {
	width: 320rpx;
	height: 320rpx;
	border-radius: 160rpx;
	background: #FCE9BC;
	margin: 60rpx auto 0px auto;
	overflow: hidden;
}

.qcode_inner {
	width: 280rpx;
	height: 280rpx;
	border-radius: 140rpx;
	background: #F5BA47;
	margin: 20rpx auto 0px auto;
	overflow: hidden;
	color: #fff;
}

.qcode_inner image {

	height: 140rpx;
	width: 140rpx;
	margin: 30rpx auto 10rpx auto;
	display: block;

}

.qcode_inner text {
	width: 180rpx;
	text-align: center;
	margin: 0rpx auto;
	display: block;
	font-size: 36rpx;
}

/* 底部栏 */
.action-section1 {
	/* #ifdef H5 */
	margin-bottom: 230upx;
	/* #endif */

	/* #ifndef H5 */
	margin-bottom: 80upx;
	/* #endif */
	position: fixed;
	left: 100upx;
	bottom: 35upx;
	z-index: 99;
	display: flex;
	padding: 0 50upx;

	.tip-btn {
		padding: 0 30upx;
		margin: 0;
		border-radius: 10px;
		height: 70upx;
		line-height: 70upx;
		font-size: $font-lg;
		background: $nav-text;
		color: $nav-bg;
		border: 2upx solid $nav-color-blue;
	}
}
</style>
